<template>
  <form-wrap :rules="rules" :schema="formSchema" @register="formRegister" />
</template>
<script setup lang="ts">
  import { getApi, listAllDataSourceInfoApi } from '@/api/tenant/tenant-info';
  import { useForm } from '@/hooks/form';
  import { useValidator } from '@/hooks/validator';

  const props = defineProps({
    currentId: {
      type: String,
      default: () => null,
    },
  });

  const formSchema = reactive<FormSchema[]>([
    { field: 'id', hidden: true },
    {
      field: 'code',
      label: '编码',
      type: 'Input',
      props: {
        disabled: true,
      },
    },
    {
      field: 'name',
      label: '名称',
      type: 'Input',
      props: {
        maxlength: 100,
      },
    },
    {
      field: 'domain',
      label: '域名',
      type: 'Input',
      props: {
        maxlength: 200,
      },
    },
    {
      field: 'dataSourceId',
      label: '数据源',
      type: 'Select',
      props: {
        fieldNames: {
          value: 'id',
          label: 'name',
        },
      },
      optionApi() {
        return listAllDataSourceInfoApi();
      },
    },
    {
      field: 'state',
      label: '启用状态',
      type: 'Select',
      enumName: 'State',
      value: 2,
    },
  ]);

  const { required } = useValidator();

  const rules = reactive({
    name: [required()],
    domain: [required()],
    dataSourceId: [required()],
    state: [required()],
  });

  const { formRegister, formMethods } = useForm();
  const { setValues, submitForm } = formMethods;

  const submit = async () => {
    return await submitForm();
  };

  watch(
    () => props.currentId,
    async (currentId) => {
      const res = await getApi(currentId);
      setValues(res);
    },
    {
      deep: true,
      immediate: true,
    }
  );

  defineExpose({
    submit,
  });
</script>
